package com.bdqn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * HelloController
 *
 * @author LILIBO
 * @since 2022-12-27
 */
@Controller
// @RequestMapping("/hello")
public class HelloController /* extends AbstractController */ {

    @GetMapping("/demo6")
    public String demo6(Model model, @RequestBody String body) {

        // 设置到Page作用域中的数据
        model.addAttribute("name", body);

        return "demo"; // 视图名称
    }

    @GetMapping("/demo5/{name}")
    public String demo5(Model model, @PathVariable("name") String name) {
        // 模拟产生异常
        // 设置到Page作用域中的数据
        model.addAttribute("name", name);

        return "demo"; // 视图名称
    }

    @GetMapping("/demo4")
    public String demo4(Model model, @RequestParam(name = "name", required = false, defaultValue = "曹操") String name) {
        // 模拟产生异常
        int n = 1 / 0; // 异常
        // 设置到Page作用域中的数据
        model.addAttribute("name", name);

        return "demo"; // 视图名称
    }

    // @RequestMapping(value = "/demo3", method = RequestMethod.POST)
    @GetMapping("/demo3")
    public String demo3(Model model) {
        // 设置到Page作用域中的数据
        model.addAttribute("name", "张飞");

        return "demo"; // 视图名称
    }


    @RequestMapping("/demo2")
    public String demo2(Model model, HttpServletRequest request) {
        String name = request.getParameter("name");
        // 设置到Page作用域中的数据
        model.addAttribute("name", "张飞");

        request.setAttribute("name", "关羽");
        return "demo"; // 视图名称
    }


    @RequestMapping("/demo1")
    public ModelAndView demo1(ModelAndView modelAndView) {
        modelAndView.addObject("name", "吕布");
        // "/WEB-INF/jsp/" + "demo" + ".jsp"
        modelAndView.setViewName("demo");
        return modelAndView; // 返回的字符串表示的就是视图名称
    }


    /**
     * 捕获异常信息，设置到作用域，跳转到统一的异常处理页面
     */
    // @ExceptionHandler()
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        // 将异常信息设置到作用域
        request.setAttribute("e", e);
        // 跳转到统一的异常处理页面
        return "error";
    }

    /* @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("Spring MVC框架搭建成功！");
        ModelAndView modelAndView = new ModelAndView();
        // Page作用域（Page、Request、Session、Application）
        modelAndView.addObject("name", "貂蝉");

        // "/WEB-INF/jsp/" + "demo" + ".jsp"
        // /WEB-INF/jsp/demo.jsp
        modelAndView.setViewName("demo");
        // request.getRequestDispatcher("/WEB-INF/jsp/demo.jsp").forward(request, response);

        return modelAndView;
    } */

}
